<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式图 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 进度条 -->
      <el-steps
        :space="200"
        :active="activeIndex * 1"
        align-center
        finish-status="success"
      >
        <el-step title="基础信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTaPLeave"
          @tab-click="tabClicked"
        >
          <!-- 基础信息 -->
          <el-tab-pane label="基础信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="allCateList"
                :props="allCateListProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染动态参数的表单 -->
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(subItem, index) in item.attr_vals"
                  :key="index"
                  :label="subItem"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染静态属性的表单 -->
            <el-form-item
              v-for="item in onlyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input
                placeholder="请输入内容"
                v-model="item.attr_vals"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :headers="headerObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible">
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash"

export default {
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs:[]
      },
      allCateList: [], //商品分类的数据列表
      allCateListProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      manyTableData: [], //动态参数列表数组
      onlyTableData: [], //静态属性列表数据
      //上传图片的url地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      //图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      previewPath: "",
      previewVisible: false,
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    //获取商品分类数据列表
    getCateList() {
      this.axios.get("categories").then((res) => {
        let result = res.data;
        if (result.meta.status !== 200) {
          return this.$message.error("获取商品分类失败");
        }
        this.allCateList = result.data;
      });
    },
    //监听选择分类的选中操作
    handleChange() {
      //判断选中的是否为三级分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        this.$message.error("请选择三级分类");
        return;
      }
      console.log(this.addForm);
    },
    beforeTaPLeave(activeName, oldActiveName) {
      if (oldActiveName == "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    tabClicked() {
      // console.log(this.activeIndex);
      //证明访问的时动态参数面板
      if (this.activeIndex === "1") {
        //获取动态参数
        this.axios
          .get(`categories/${this.id}/attributes`, {
            params: { sel: "many" },
          })
          .then((res) => {
            let result = res.data;
            // console.log(result.data);
            if (result.meta.status !== 200) {
              return this.$message.error("获取动态参数列表失败");
            }
            result.data.forEach((item) => {
              if (item.attr_vals) {
                item.attr_vals = item.attr_vals.split(",");
              }
            });
            this.manyTableData = result.data;
            console.log(this.manyTableData);
          });
      }
      if (this.activeIndex === "2") {
        //获取动态参数
        this.axios
          .get(`categories/${this.id}/attributes`, {
            params: { sel: "only" },
          })
          .then((res) => {
            let result = res.data;
            if (result.meta.status !== 200) {
              return this.$message.error("获取动态参数列表失败");
            }
            // result.data.forEach((item) => {
            //   if (item.attr_vals) {
            //     item.attr_vals = item.attr_vals.split(",");
            //   }
            // });
            this.onlyTableData = result.data;
            console.log(this.onlyTableData);
          });
      }
    },
    //处理图片预览效果
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },
    //处理删除图片的操作
    handleRemove(file) {
      // console.log(file);
      const filePath = file.response.data.tmp_path;
      this.addForm.pics.forEach((item, index) => {
        if (item.pic === filePath) {
          this.addForm.pics.splice(index, 1);
          return;
        }
      });
    },
    //监听图片上传成功事件
    handleSuccess(response) {
      // console.log(response);
      if (response.meta.status !== 200) {
        this.$message.error("图片上传失败");
      }
      this.addForm.pics.push({ pic: response.data.tmp_path });
    },
    addGood(){
      this.$refs.addFormRef.validate(valid=>{
        if (!valid) {
          return this.$message.error("请填写必要的表单项")
        }
        // 执行添加逻辑
        // console.log(this.addForm);
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(",")
        //处理动态参数
        this.manyTableData.forEach(item=>{
          const attrsObj = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(",")
          }
          form.attrs.push(attrsObj)
        })
        //处理静态属性
        this.onlyTableData.forEach(item=>{
          const attrsObj = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          }
          form.attrs.push(attrsObj)
        })
        console.log(form);
        this.axios.post("goods",form).then(res=>{
          let result = res.data
          console.log(result);
          if (result.meta.status !== 201) {
            return this.$message.error(result.meta.msg)
          }
          this.$message.success(result.meta.msg)
          this.$router.push("/goods")
        })
      })
    }
  },
  computed: {
    id() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      } else {
        return null;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tab-pane {
  text-align: left;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.el-button{
  margin: 15px 0;
  text-align: left;
}
</style>